package com.amazon.shop.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.amazon.shop.aop.SystemLog;
import com.amazon.shop.api.GetDate;
import com.amazon.shop.api.GetExample;
import com.amazon.shop.constant.ReturnConstant;
import com.amazon.shop.entity.*;
import com.amazon.shop.entity.auth.Users;
import com.amazon.shop.exception.CustomException;
import com.amazon.shop.service.*;
import com.amazon.shop.service.impl.PermissionsServiceImpl;
import com.amazon.shop.service.impl.SalesmanServiceImpl;
import com.amazon.shop.service.impl.UsersServiceImpl;
import com.amazon.shop.spapi.api.OrdersV0Api;
import com.amazon.shop.spapi.client.ApiException;
import com.amazon.shop.spapi.model.orders.*;
import com.amazon.shop.utils.CommonResult;
import com.amazon.shop.utils.RateUtils;
import com.amazon.shop.vo.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 郭非
 * @since 2021-06-12
 */
@RestController
@RequestMapping("/shop/order-simple")
@Api(tags = "订单模块")
public class OrderSimpleController {
    @Resource
    private OrderSimpleService orderSimpleService;
    @Resource
    private AmazonAuthorityService amazonAuthorityService;
    @Resource
    private AccountAuthorizationService accountAuthorizationService;
    @Resource
    private CountryService countryService;
    @Resource
    private BuyerInfoService buyerInfoService;
    @Resource
    private OrderWayBillService orderWayBillService;
    @Resource
    private ContentNotesService contentNotesService;
    @Resource
    private CommodityService commodityService;
    @Resource
    private ProductPicService productPicService;
    @Resource
    private ProductSkuService productSkuService;
    @Resource
    private ProductVariantService productVariantService;
    @Resource
    private SellerInfoService sellerInfoService;
    @Resource
    private OperationLogService operationLogService;
    @Resource
    private UsersServiceImpl usersService;
    @Resource
    private SalesmanServiceImpl salesmanService;
    @Resource
    private PermissionsServiceImpl permissionsService;
    @Resource
    private OrderPurchaseService orderPurchaseService;
    @Resource
    private CurrencyService currencyService;
    @Resource
    private OrderBackService orderBackService;
    @Resource
    private ThreadPoolExecutor executor;

    /**
     * 为订单设置业务员
     *
     * @param salesman
     * @param orderNumber
     * @param token
     * @return
     */
    @SystemLog(value = "为订单设置业务员")
    @PostMapping("/setSalesman")
    @ApiOperation(value = "为订单设置业务员")
    @Transactional
    public CommonResult setSalesman(String salesman, String orderNumber, String token) {
        boolean flag = permissionsService.getPermissionList(token, "36");
        if (flag) {
            QueryWrapper<Salesman> salesmanQueryWrapper = new QueryWrapper<>();

            //根据业务员名字查询编号
            salesmanQueryWrapper.eq("salesman_name", salesman);
            Salesman salesmanServiceOne = salesmanService.getOne(salesmanQueryWrapper);
            String salesmanId = salesmanServiceOne.getSalesmanId();

            //为订单设置业务员编号
            Orders orders = orderSimpleService.getById(orderNumber);
            orders.setSalesmanId(salesmanId);

            //更新订单信息
            boolean update = orderSimpleService.updateById(orders);
            if (update) {
                String number = orders.getOrderNumber();
                //根据token查询业务员名字
                String userRealName = usersService.getUserRealName(token);
                return CommonResult.success("设置业务员成功")
                        .put("list", number)
                        .put("salesman", userRealName);
            } else {
                return CommonResult.error("设置业务员失败");
            }
        }
        throw new CustomException(ReturnConstant.NO_PERMISSION_CODE
                , ReturnConstant.NO_PERMISSION_MESSAGE);
    }

    /**
     * 更新订单状态
     *
     * @param orderStatusVo
     * @return
     */
    @SystemLog(value = "更新订单状态")
    @PostMapping("/updateStatus")
    @ApiOperation(value = "更新订单状态")
    @Transactional
    public CommonResult updateStatus(@RequestBody OrderStatusVo orderStatusVo, String token) {
        boolean flag = permissionsService.getPermissionList(token, "44");
        if (flag){
            String number = orderStatusVo.getOrderNumber();
            Orders orders = orderSimpleService.getById(number);

            BeanUtils.copyProperties(orderStatusVo, orders);
            boolean update = orderSimpleService.updateById(orders);

            if (update) {
                String userRealName = usersService.getUserRealName(token);
                return CommonResult.success("订单状态更新成功")
                        .put("list", number)
                        .put("salesman", userRealName);
            } else {
                return CommonResult.error("订单状态更新失败");
            }
        } else {
            throw new CustomException(ReturnConstant.NO_PERMISSION_CODE
                    , ReturnConstant.NO_PERMISSION_MESSAGE);
        }
    }

    /**
     * 拉取亚马逊订单
     *
     * @return
     * @throws ApiException
     */
    public List<OrderList> pullOrders() throws ApiException {
        List<OrdersV0Api> ordersV0ApiList = getOrdersV0Api();
        List<OrderList> orderLists = ordersV0ApiList.stream().map((ordersV0Api) -> {

            List<AccountAuthorization> authorizations = accountAuthorizationService.list();

            //根据站点列表获取对应国家信息列表
            List<String> countryIdList = authorizations.stream().map((account) -> {
                String countryId = account.getCountryId();
                return countryId;
            }).collect(Collectors.toList());
            List<Country> countryList = countryService.listByIds(countryIdList);

            //根据国家信息查询对应站点信息
            List<String> marketplaceIdList = countryList.stream().map((country) -> {
                String marketplaceId = country.getMarketplaceId();
                return marketplaceId;
            }).collect(Collectors.toList());


            //获得指定时间之后的订单列表
            GetOrdersResponse amazonOrder = null;
            try {
                amazonOrder = new GetDate().getAmazonOrder(
                        ordersV0Api
                        , marketplaceIdList
                        , "2001-06-14T02:05:14.302Z");
            } catch (ApiException e) {
                e.printStackTrace();
            }
            OrderList orderList = amazonOrder.getPayload().getOrders();
            return orderList;
        }).collect(Collectors.toList());
        return orderLists;
    }

    /**
     * 保存订单
     *
     * @return
     */
    @Transactional
    public void saveOrders() throws ApiException, ExecutionException, InterruptedException {

        //开始异步任务并将任务交给自定义线程池管理
        CompletableFuture<List<OrderList>> pullOrdersFuture = CompletableFuture.supplyAsync(() -> {
            List<OrderList> orderLists = null;

            //删除之前先保存备份信息
            List<Orders> ordersList = orderSimpleService.list();
            if (ordersList.size() > 0) {
                List<OrderBack> orderBacks = ordersList.stream().map((orders) -> {
                    OrderBack orderBack = new OrderBack();
                    //属性对拷
                    BeanUtils.copyProperties(orders, orderBack);
                    //设置订单号
                    orderBack.setOrderId(orders.getOrderNumber());
                    return orderBack;
                }).collect(Collectors.toList());
                orderBackService.saveOrUpdateBatch(orderBacks);
            }

            //拉取之前删除信息
            //删除买家信息
            buyerInfoService.remove(null);

            //删除商品信息
            commodityService.remove(null);

            //删除卖家信息
            sellerInfoService.remove(null);

            //删除订单信息
            orderSimpleService.remove(null);
            try {
                orderLists = pullOrders();
            } catch (ApiException e) {
                throw new CustomException(ReturnConstant.PULL_ORDERS_ERROR_CODE
                        , ReturnConstant.PULL_ORDERS_ERROR_MESSAGE);
            }
            return orderLists;
        }, executor);

        //拉取订单并封装对应信息
        CompletableFuture<List<Orders>> ordersFuture = pullOrdersFuture.thenApplyAsync((orderLists) -> {
            List<List<Orders>> collect = orderLists.stream().map((orderList) -> {
                List<Orders> ordersList = orderList.stream().map((order) -> {
                    Orders orders = new Orders();
                    //获取订单状态
                    String status = order.getOrderStatus().getValue();
                    //获取销售单号
                    String amazonOrderId = order.getAmazonOrderId();
                    //获取日期
                    String purchaseDate = order.getPurchaseDate();
                    //格式化日期
                    //转换时区格式
                    DateFormat formatOne = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
                    DateFormat formatTwo = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.UK);
                    DateFormat formatThree = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date parseOne = null;
                    Date parseTwo = null;
                    String parseThree = null;

                    try {
                        parseOne = formatOne.parse(purchaseDate);
                        parseTwo = formatTwo.parse(parseOne.toString());
                        parseThree = formatThree.format(parseTwo);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    if (!StringUtils.isEmpty(status)) {
                        orders.setStatus(status);
                    }
                    if (!StringUtils.isEmpty(amazonOrderId)) {
                        orders.setAmazonOrderId(amazonOrderId);
                    }
                    if (!StringUtils.isEmpty(purchaseDate)) {
                        orders.setGmtCreated(parseThree);
                    }
                    //设置自定义订单编号
                    orders.setOrderNumber(amazonOrderId.replace("-", "") + "order");
                    return orders;
                }).collect(Collectors.toList());
                //批量保存订单信息
                orderSimpleService.saveOrUpdateBatch(ordersList);
                return ordersList;
            }).collect(Collectors.toList());

            //返回订单信息列表
            List<Orders> list = orderSimpleService.list();
            return list;
        }, executor);

        //根据订单号获取卖家信息
        CompletableFuture<Void> sellerFuture = ordersFuture.thenAcceptAsync((list) -> {
            List<OrdersV0Api> ordersV0ApiList = getOrdersV0Api();
            List<List<SellerInfo>> collect = ordersV0ApiList.stream().map((ordersV0Api) -> {

                List<SellerInfo> sellerInfoList = list.stream().map((orders) -> {
                    String amazonOrderId = orders.getAmazonOrderId();
                    SellerInfo sellerInfo = new SellerInfo();
                    try {

                        GetOrderResponse order = ordersV0Api.getOrder(amazonOrderId);
                        Money orderTotal = order.getPayload().getOrderTotal();
                        if (orderTotal != null) {
                            //价格信息
                            String amount = orderTotal.getAmount();
                            if (!StringUtils.isEmpty(amount)) {
                                //处理价格
                                BigDecimal bigDecimalAmount = new BigDecimal(amount);
                                BigDecimal serviceCharge = bigDecimalAmount.multiply(new BigDecimal("0.15"));
                                BigDecimal price = bigDecimalAmount.subtract(serviceCharge);

                                //设置钱数
                                sellerInfo.setMoney(price);
                                sellerInfo.setServiceCharge(serviceCharge);
                                sellerInfo.setOrderPrice(bigDecimalAmount);
                            }
                        }
                        //设置卖家账户
                        QueryWrapper<AccountAuthorization> accountAuthorizationQueryWrapper = new QueryWrapper<>();
                        accountAuthorizationQueryWrapper.eq("seller_number", amazonOrderId);
                        AccountAuthorization accountAuthorization = accountAuthorizationService.getOne(accountAuthorizationQueryWrapper);
                        if (accountAuthorization != null) {
                            String authorizationAccount = accountAuthorization.getAuthorizationAccount();
                            sellerInfo.setSellerAccount(authorizationAccount);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    //设置卖家编号
                    sellerInfo.setSellerNum(amazonOrderId);
                    return sellerInfo;
                }).collect(Collectors.toList());

                //批量增加卖家信息
                sellerInfoService.saveOrUpdateBatch(sellerInfoList);
                //将卖家编号保存到订单中
                for (SellerInfo sellerInfo : sellerInfoList) {
                    String sellerNum = sellerInfo.getSellerNum();
                    QueryWrapper<Orders> ordersQueryWrapper = new QueryWrapper<>();
                    ordersQueryWrapper.eq("amazon_order_id", sellerNum);
                    Orders orders = orderSimpleService.getOne(ordersQueryWrapper);
                    orders.setSellerId(sellerNum);
                    orderSimpleService.updateById(orders);
                }
                return sellerInfoList;
            }).collect(Collectors.toList());

        }, executor);

        //根据订单号获取买家信息
        CompletableFuture<Void> buyerFuture = ordersFuture.thenAcceptAsync((list) -> {
            List<OrdersV0Api> ordersV0ApiList = getOrdersV0Api();
            List<List<BuyerInfo>> listList = ordersV0ApiList.stream().map((ordersV0Api) -> {
                try {
                    List<BuyerInfo> buyerInfoList = list.stream().map((order) -> {
                        String orderId = order.getAmazonOrderId();

                        BuyerInfo buyerInfo = new BuyerInfo();
                        //设置自定义买家编号
                        buyerInfo.setId(orderId.replace("-", "") + "buyer");
                        buyerInfo.setAmazonOrderId(orderId);
                        //获取亚马逊订单中买家信息
                        GetOrderBuyerInfoResponse orderBuyerResponse = null;
                        //获取亚马逊订单中地址信息
                        GetOrderAddressResponse orderAddressResponse = null;

                        OrderBuyerInfo buyerInfoPayload = null;
                        OrderAddress orderAddressPayload = null;
                        try {
                            orderBuyerResponse = ordersV0Api.getOrderBuyerInfo(orderId);
                            orderAddressResponse = ordersV0Api.getOrderAddress(orderId);
                            buyerInfoPayload = orderBuyerResponse.getPayload();
                            orderAddressPayload = orderAddressResponse.getPayload();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        String company = null;
                        String amazonOrderId = null;
                        String buyerEmail = null;
                        String buyerName = null;
                        String city = null;
                        String phone = null;
                        String countryCode = null;
                        String stateOrRegion = null;
                        try {
                            company = buyerInfoPayload.getBuyerTaxInfo().getCompanyLegalName();
                            Address shippingAddress = orderAddressPayload.getShippingAddress();
                            //买家信息
                            amazonOrderId = buyerInfoPayload.getAmazonOrderId();
                            buyerEmail = buyerInfoPayload.getBuyerEmail();
                            buyerName = buyerInfoPayload.getBuyerName();
                            //地址信息
                            city = shippingAddress.getCity();
                            phone = shippingAddress.getPhone();
                            countryCode = shippingAddress.getCountryCode();
                            stateOrRegion = shippingAddress.getStateOrRegion();
                        } catch (Exception e) {

                        }
                        if (!StringUtils.isEmpty(amazonOrderId)) {
                            buyerInfo.setAmazonOrderId(amazonOrderId);
                        }
                        if (!StringUtils.isEmpty(countryCode)) {
                            buyerInfo.setCountry(countryCode);
                        }
                        if (!StringUtils.isEmpty(buyerEmail)) {
                            buyerInfo.setMail(buyerEmail);
                        }
                        if (!StringUtils.isEmpty(buyerName)) {
                            buyerInfo.setName(buyerName);
                        }
                        if (!StringUtils.isEmpty(city)) {
                            buyerInfo.setCity(city);
                        }
                        if (!StringUtils.isEmpty(phone)) {
                            buyerInfo.setPhone(phone);
                        }
                        if (!StringUtils.isEmpty(company)) {
                            buyerInfo.setCompany(company);
                        }
                        if (!StringUtils.isEmpty(stateOrRegion)) {
                            buyerInfo.setProvince(stateOrRegion);
                        }
                        return buyerInfo;
                    }).collect(Collectors.toList());

                    //批量保存买家信息
                    buyerInfoService.saveOrUpdateBatch(buyerInfoList);

                    //将买家编号保存到对应订单中
                    for (BuyerInfo buyerInfo : buyerInfoList) {
                        try {
                            String buyerInfoId = buyerInfo.getId();
                            String amazonOrderId = buyerInfo.getAmazonOrderId();
                            QueryWrapper<Orders> ordersQueryWrapper = new QueryWrapper<>();
                            ordersQueryWrapper.eq("amazon_order_id", amazonOrderId);
                            Orders orders = orderSimpleService.getOne(ordersQueryWrapper);
                            orders.setBuyerId(buyerInfoId);
                            orderSimpleService.updateById(orders);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    return buyerInfoList;
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }).collect(Collectors.toList());
        }, executor);

        //根据订单号获取商品信息
        CompletableFuture<Void> itemFuture = ordersFuture.thenAcceptAsync((list) -> {

            for (Orders orders : list) {
                String id = orders.getAmazonOrderId();
                List<OrdersV0Api> ordersV0Apis = getOrdersV0Api();
                List<Object> collect = ordersV0Apis.stream().map((ordersV0Api) -> {
                    //获取亚马逊订单中商品信息
                    OrderItemList orderItems = null;
                    OrderItemsList payload = null;
                    GetOrderItemsResponse orderItemsResponse = null;
                    try {
                        orderItemsResponse = ordersV0Api.getOrderItems(id, null);
                        payload = orderItemsResponse.getPayload();
                        orderItems = payload.getOrderItems();
                    } catch (ApiException e) {
                        e.printStackTrace();
                    }
                    List<Commodity> commodityList = orderItems.stream().map((item) -> {
                        Commodity commodity = new Commodity();
                        commodity.setAmazonOrderId(id);

                        //商品信息
                        String sellerSKU = null;
                        Integer numberOfItems = null;
                        String amount = null;
                        String title = null;
                        String currencyCode = null;
                        try {
                            sellerSKU = item.getSellerSKU();
                            numberOfItems = item.getProductInfo().getNumberOfItems();
                            title = item.getTitle();
                            amount = item.getItemPrice().getAmount();
                            currencyCode = item.getItemPrice().getCurrencyCode();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        if (!StringUtils.isEmpty(sellerSKU)) {
                            //设置商品sku
                            commodity.setSku(sellerSKU);
                            //通过sku查询产品编号
                            QueryWrapper<ProductSku> productSkuQueryWrapper = new QueryWrapper<>();
                            productSkuQueryWrapper.eq("sku", sellerSKU);
                            ProductSku productSku = productSkuService.getOne(productSkuQueryWrapper);
                            String productId = productSku.getProductId();
                            commodity.setProductId(productId);
                            //通过产品编号查询对应变体
                            QueryWrapper<ProductVariant> productVariantQueryWrapper = new QueryWrapper<>();
                            productVariantQueryWrapper.eq("product_id", productId);
                            ProductVariant productVariant = productVariantService.getOne(productVariantQueryWrapper);
                            if (productVariant != null) {
                                String variant = productVariant.getVariant();
                                commodity.setVariant(variant);
                            }
                        }
                        if (amount != null) {
                            //设置价格
                            commodity.setPrice(new BigDecimal(amount));
                        }
                        if (!StringUtils.isEmpty(title)) {
                            commodity.setTitle(title);
                        }
                        if (numberOfItems != null && numberOfItems >= 0) {
                            commodity.setCount(numberOfItems);
                        }
                        if (!StringUtils.isEmpty(currencyCode)) {
                            commodity.setCurrencyCode(currencyCode);
                        }
                        //设置自定义商品编号
                        commodity.setNumber(id.replace("-", "") + "commodity");
                        return commodity;
                    }).collect(Collectors.toList());

                    //批量保存商品信息
                    commodityService.saveOrUpdateBatch(commodityList);
                    for (Commodity commodity : commodityList) {
                        try {
                            String number = commodity.getNumber();
                            String orderId = commodity.getAmazonOrderId();
                            QueryWrapper<Orders> ordersQueryWrapper = new QueryWrapper<>();
                            ordersQueryWrapper.eq("amazon_order_id", orderId);
                            Orders orderSimpleServiceOne = orderSimpleService.getOne(ordersQueryWrapper);
                            orderSimpleServiceOne.setCommodityId(number);
                            orderSimpleService.updateById(orderSimpleServiceOne);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    return null;
                }).collect(Collectors.toList());
            }
        }, executor);

        //等待所有异步任务结束后放行
        CompletableFuture.allOf(pullOrdersFuture, ordersFuture, sellerFuture, buyerFuture, itemFuture).get();
    }

    /**
     * 根据订单编号获取订单详情信息
     *
     * @return
     */
    @GetMapping("/getOrderById")
    @ApiOperation(value = "根据订单编号获取订单详情信息")
    public CommonResult getOrderById(String orderId, String token) {
        boolean flag = permissionsService.getPermissionList(token, "36");
        if (flag) {
            Orders orders = orderSimpleService.getById(orderId);
            OrderSimple orderSimple = new OrderSimple();
            //对应属性对拷
            BeanUtils.copyProperties(orders, orderSimple);

            //根据买家编号查询具体的买家信息
            String ordersBuyerId = orders.getBuyerId();
            if (!StringUtils.isEmpty(ordersBuyerId)) {
                BuyerInfo buyerInfo = buyerInfoService.getById(ordersBuyerId);
                BuyerInfoVo buyerInfoVo = new BuyerInfoVo();
                BeanUtils.copyProperties(buyerInfo, buyerInfoVo);
                orderSimple.setBuyer(buyerInfoVo);
            }

            //根据销售单号查询卖家信息
            String amazonOrderId = orders.getAmazonOrderId();
            SellerInfo sellerInfo = sellerInfoService.getById(amazonOrderId);
            if (sellerInfo != null) {
                orderSimple.setSellerInfo(sellerInfo);
            }

            //根据商品编号查询具体的商品信息
            String commodityId = orders.getCommodityId();
            if (!StringUtils.isEmpty(commodityId)) {
                Commodity commodity = commodityService.getById(commodityId);
                CommodityVo commodityVo = new CommodityVo();
                BeanUtils.copyProperties(commodity, commodityVo);
                //通过sku查询具体的图片
                String sku = commodity.getSku();
                if (!StringUtils.isEmpty(sku)) {
                    QueryWrapper<ProductPic> productPicQueryWrapper = new QueryWrapper<>();
                    productPicQueryWrapper.eq("sku", sku);
                    List<ProductPic> productPicList = productPicService.list(productPicQueryWrapper);
                    List<ProductPicVo> productPicVoList = productPicList.stream().map((pic) -> {
                        ProductPicVo productPicVo = new ProductPicVo();
                        BeanUtils.copyProperties(pic, productPicVo);
                        return productPicVo;
                    }).collect(Collectors.toList());
                    commodityVo.setPixMap(productPicVoList);


                    //获取商品价格
                    BigDecimal price = commodity.getPrice();

                    //计算成本 成本 = 采购单价格 + 运单价格
                    //根据订单编号查询采购单信息
                    BigDecimal money = new BigDecimal("0.00");
                    try {
                        QueryWrapper<OrderPurchase> orderPurchaseQueryWrapper = new QueryWrapper<>();
                        orderPurchaseQueryWrapper.eq("order_id", orderId);
                        OrderPurchase orderPurchase = orderPurchaseService.getOne(orderPurchaseQueryWrapper);
                        if (orderPurchase != null) {
                            money = orderPurchase.getMoney();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    //根据订单编号查询运单信息
                    BigDecimal wayBillPrice = new BigDecimal("0.00");
                    try {
                        QueryWrapper<OrderWayBill> orderWayBillQueryWrapper = new QueryWrapper<>();
                        orderWayBillQueryWrapper.eq("about_order", orderId);
                        OrderWayBill orderWayBill = orderWayBillService.getOne(orderWayBillQueryWrapper);
                        wayBillPrice = orderWayBill.getPrice();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    //设置成本
                    BigDecimal basicPrice = wayBillPrice.add(money);
                    commodityVo.setBasicPrice(basicPrice);

                    //计算利润 利润等于 价格减去成本
                    String currencyCode = commodity.getCurrencyCode();
                    Double exchangeMoneyRate = RateUtils.exchangeMoney("CNY", currencyCode);
                    BigDecimal bigDecimal = BigDecimal.valueOf(exchangeMoneyRate);
                    BigDecimal exchangePrice = price.divide(bigDecimal, 2, BigDecimal.ROUND_HALF_UP);
                    BigDecimal profit = exchangePrice.subtract(basicPrice);
                    commodityVo.setProfit(profit);

                    //通过币种代号查询币种
                    QueryWrapper<Currency> currencyQueryWrapper = new QueryWrapper<>();
                    currencyQueryWrapper.eq("currency_code", currencyCode);
                    Currency currency = currencyService.getOne(currencyQueryWrapper);

                    //设置币种
                    String currencyName = currency.getCurrencyName();
                    commodityVo.setCurrency(currencyName);
                    orderSimple.setCommodityVo(commodityVo);
                }
            }

            //通过订单号查询对应的备注信息
            ContentNotes contentNotes = contentNotesService.getById(orderId);
            if (contentNotes != null) {
                ContentNotesVo contentNotesVo = new ContentNotesVo();
                BeanUtils.copyProperties(contentNotes, contentNotesVo);
                orderSimple.setNote(contentNotesVo);
            }

            //通过订单号查询对应的运单信息
            OrderWayBill orderWayBill = null;
            try {
                QueryWrapper<OrderWayBill> orderWayBillQueryWrapper = new QueryWrapper<>();
                orderWayBillQueryWrapper.eq("about_order", orderId);
                orderWayBill = orderWayBillService.getOne(orderWayBillQueryWrapper);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (orderWayBill != null) {
                OrderWayBillVo orderWayBillVo = new OrderWayBillVo();
                BeanUtils.copyProperties(orderWayBill, orderWayBillVo);
                //处理时间
                String gmtCreated = orderWayBill.getGmtCreated();
                DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date addTime = null;
                try {
                    addTime = dateFormat.parse(gmtCreated);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                //设置运单时间
                orderWayBillVo.setAddTime(addTime);

                //查询运单对应商品信息
                if (!StringUtils.isEmpty(commodityId)) {
                    Commodity commodity = commodityService.getById(commodityId);
                    CommodityVo commodityVo = new CommodityVo();
                    BeanUtils.copyProperties(commodity, commodityVo);
                    //通过sku查询具体的图片
                    String sku = commodity.getSku();
                    if (!StringUtils.isEmpty(sku)) {
                        QueryWrapper<ProductPic> productPicQueryWrapper = new QueryWrapper<>();
                        productPicQueryWrapper.eq("sku", sku);
                        List<ProductPic> productPicList = productPicService.list(productPicQueryWrapper);
                        List<ProductPicVo> productPicVoList = productPicList.stream().map((pic) -> {
                            ProductPicVo productPicVo = new ProductPicVo();
                            BeanUtils.copyProperties(pic, productPicVo);
                            return productPicVo;
                        }).collect(Collectors.toList());
                        commodityVo.setPixMap(productPicVoList);
                    }
                    orderWayBillVo.setCommodityVo(commodityVo);
                }
                orderSimple.setWayBill(orderWayBillVo);

                //根据订单号查询对应日志信息
                List<OperationLog> operationLogList = null;
                try {
                    QueryWrapper<OperationLog> operationLogQueryWrapper = new QueryWrapper<>();
                    operationLogQueryWrapper.eq("table_id", orderId);
                    operationLogList = operationLogService.list(operationLogQueryWrapper);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                List<OperationLogVo> operationLogVoList = operationLogList.stream().map((operationLog) -> {
                    OperationLogVo operationLogVo = new OperationLogVo();
                    BeanUtils.copyProperties(operationLog, operationLogVo);
                    return operationLogVo;
                }).collect(Collectors.toList());
                orderSimple.setLogList(operationLogVoList);

                //根据订单号查询对应采购单
                OrderPurchase orderPurchase = null;
                try {
                    QueryWrapper<OrderPurchase> orderPurchaseQueryWrapper = new QueryWrapper<>();
                    orderPurchaseQueryWrapper.eq("order_id", orderId);
                    orderPurchase = orderPurchaseService.getOne(orderPurchaseQueryWrapper);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                OrderPurchaseVo orderPurchaseVo = new OrderPurchaseVo();

                ProductPicVo productPicVo = new ProductPicVo();
                //设置图片路径
                String pixMap = orderPurchase.getPixMap();
                productPicVo.setPath(pixMap);

                BeanUtils.copyProperties(orderPurchase, orderPurchaseVo);

                //设置采购单
                orderSimple.setOrderPurchaseVo(orderPurchaseVo);
                return CommonResult.success().put("data", orderSimple);
            }
        }
        throw new CustomException(ReturnConstant.NO_PERMISSION_CODE
                , ReturnConstant.NO_PERMISSION_MESSAGE);
    }

    /**
     * 获取订单列表
     *
     * @return
     */
    @GetMapping("/getOrders")
    @ApiOperation(value = "获取订单列表")
    public CommonResult getOrders(String token) throws ExecutionException, InterruptedException, ApiException {
        boolean flag = permissionsService.getPermissionList(token, "36");
        if (flag) {
            try {
                //拉取订单后保存到本地
                saveOrders();
            } catch (ApiException e) {
                throw new CustomException(ReturnConstant.PULL_ORDERS_ERROR_CODE
                        , ReturnConstant.PULL_ORDERS_ERROR_MESSAGE);
            } catch (Exception e) {
                e.printStackTrace();
            }

            //查询订单列表
            List<Orders> ordersList = orderSimpleService.list();
            List<OrderSimple> orderSimpleList = ordersList.stream().map((orders) -> {
                OrderSimple orderSimple = new OrderSimple();
                String orderNumber = orders.getOrderNumber();

                //根据买家编号获取对应的买家信息
                String buyerId = orders.getBuyerId();
                BuyerInfo buyerInfo = buyerInfoService.getById(buyerId);
                if (buyerInfo != null) {
                    BuyerInfoVo buyerInfoVo = new BuyerInfoVo();
                    BeanUtils.copyProperties(buyerInfo, buyerInfoVo);
                    orderSimple.setBuyer(buyerInfoVo);
                }

                //根据商品编号获取对应商品信息
                String commodityId = orders.getCommodityId();
                Commodity commodity = commodityService.getById(commodityId);
                CommodityVo commodityVo = new CommodityVo();
                if (commodity != null) {
                    BeanUtils.copyProperties(commodity, commodityVo);
                    //根据sku查询对应商品图片
                    String sku = commodity.getSku();
                    QueryWrapper<ProductPic> productPicQueryWrapper = new QueryWrapper<>();
                    productPicQueryWrapper.eq("sku", sku);
                    List<ProductPic> productPicList = productPicService.list(productPicQueryWrapper);
                    if (productPicList != null) {
                        List<ProductPicVo> productPicVos = productPicList.stream().map((productPic) -> {
                            ProductPicVo productPicVo = new ProductPicVo();
                            productPicVo.setPath(productPic.getPath());
                            return productPicVo;
                        }).collect(Collectors.toList());
                        commodityVo.setPixMap(productPicVos);
                    }

                    //获取商品价格
                    BigDecimal price = commodity.getPrice();

                    //计算成本 成本 = 采购单价格 + 运单价格
                    //根据订单编号查询采购单信息
                    BigDecimal money = null;
                    try {
                        money = new BigDecimal("0.00");
                        QueryWrapper<OrderPurchase> orderPurchaseQueryWrapper = new QueryWrapper<>();
                        orderPurchaseQueryWrapper.eq("order_id", orderNumber);
                        OrderPurchase orderPurchase = orderPurchaseService.getOne(orderPurchaseQueryWrapper);
                        if (orderPurchase != null) {
                            money = orderPurchase.getMoney();
                        }
                    } catch (CustomException e) {
                        e.printStackTrace();
                    }

                    //根据订单编号查询运单信息
                    BigDecimal wayBillPrice = null;
                    try {
                        wayBillPrice = new BigDecimal("0.00");
                        QueryWrapper<OrderWayBill> orderWayBillQueryWrapper = new QueryWrapper<>();
                        orderWayBillQueryWrapper.eq("about_order", orderNumber);
                        OrderWayBill orderWayBill = orderWayBillService.getOne(orderWayBillQueryWrapper);
                        if (orderWayBill != null) {
                            wayBillPrice = orderWayBill.getPrice();
                        }
                    } catch (CustomException e) {
                        e.printStackTrace();
                    }

                    String currencyCode = commodity.getCurrencyCode();
                    //设置成本
                    if (wayBillPrice != null && money != null) {
                        BigDecimal basicPrice = wayBillPrice.add(money);
                        commodityVo.setBasicPrice(basicPrice);
                        if (!StringUtils.isEmpty(currencyCode)) {
                            //计算利润 利润等于 价格减去成本
                            try {
                                Double exchangeMoneyRate = RateUtils.exchangeMoney("CNY", currencyCode);
                                BigDecimal exchangePrice = price.multiply(new BigDecimal(exchangeMoneyRate)).setScale(2, RoundingMode.HALF_UP);
                                BigDecimal profit = exchangePrice.subtract(basicPrice);
                                commodityVo.setProfit(profit);

                                //通过币种代号查询币种
                                QueryWrapper<Currency> currencyQueryWrapper = new QueryWrapper<>();
                                currencyQueryWrapper.eq("currency_code", currencyCode);
                                Currency currency = currencyService.getOne(currencyQueryWrapper);

                                //设置币种
                                String currencyName = currency.getCurrencyName();
                                commodityVo.setCurrency(currencyName);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }

                    //根据sku查询产品id 通过产品id查询对应变体
                    ProductSku productSku = null;
                    try {
                        QueryWrapper<ProductSku> productSkuQueryWrapper = new QueryWrapper<>();
                        productSkuQueryWrapper.eq("sku", sku);
                        productSku = productSkuService.getOne(productSkuQueryWrapper);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if (productSku != null) {
                        String productId = productSku.getProductId();
                        QueryWrapper<ProductVariant> productVariantQueryWrapper = new QueryWrapper<>();
                        productVariantQueryWrapper.eq("product_id", productId);
                        ProductVariant productVariant = productVariantService.getOne(productVariantQueryWrapper);
                        if (productVariant != null) {
                            String variant = productVariant.getVariant();
                            if (!StringUtils.isEmpty(variant)) {
                                commodityVo.setVariant(variant);
                            }
                        }
                    }
                    orderSimple.setCommodityVo(commodityVo);
                }

                //根据订单id查询对应备注信息
                ContentNotes contentNotes = null;
                try {
                    QueryWrapper<ContentNotes> contentNotesQueryWrapper = new QueryWrapper<>();
                    contentNotesQueryWrapper.eq("order_id", orderNumber);
                    contentNotes = contentNotesService.getOne(contentNotesQueryWrapper);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (contentNotes != null) {
                    ContentNotesVo contentNotesVo = new ContentNotesVo();
                    BeanUtils.copyProperties(contentNotes, contentNotesVo);
                    orderSimple.setNote(contentNotesVo);
                }

                //根据销售单号查询卖家信息
                SellerInfo sellerInfo = null;
                try {
                    String amazonOrderId = orders.getAmazonOrderId();
                    sellerInfo = sellerInfoService.getById(amazonOrderId);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (sellerInfo != null) {
                    orderSimple.setSellerInfo(sellerInfo);
                }

                //根据订单id查询对应运单信息
                OrderWayBill orderWayBill = null;
                try {
                    QueryWrapper<OrderWayBill> orderWayBillQueryWrapper = new QueryWrapper<>();
                    orderWayBillQueryWrapper.eq("about_order", orderNumber);
                    orderWayBill = orderWayBillService.getOne(orderWayBillQueryWrapper);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (orderWayBill != null) {
                    OrderWayBillVo orderWayBillVo = new OrderWayBillVo();

                    //解析时间
                    String gmtCreated = orderWayBill.getGmtCreated();
                    DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date parse = null;
                    try {
                        parse = format.parse(gmtCreated);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    orderWayBillVo.setAddTime(parse);
                    //设置商品信息
                    orderWayBillVo.setCommodityVo(commodityVo);
                    //对应属性对拷
                    BeanUtils.copyProperties(orderWayBill, orderWayBillVo);
                    orderSimple.setWayBill(orderWayBillVo);
                }

                //封装日志信息
                List<OperationLog> operationLogList = null;
                try {
                    QueryWrapper<OperationLog> operationLogQueryWrapper = new QueryWrapper<>();
                    operationLogQueryWrapper.eq("table_id", orderNumber);
                    operationLogList = operationLogService.list(operationLogQueryWrapper);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (operationLogList != null) {
                    List<OperationLogVo> operationLogVoList = operationLogList.stream().map((operationLog) -> {
                        OperationLogVo operationLogVo = new OperationLogVo();
                        BeanUtils.copyProperties(operationLog, operationLogVo);
                        return operationLogVo;
                    }).collect(Collectors.toList());
                    orderSimple.setLogList(operationLogVoList);
                }

                //封装采购单信息
                OrderPurchase orderPurchase = null;
                OrderPurchaseVo orderPurchaseVo = null;
                try {
                    QueryWrapper<OrderPurchase> orderPurchaseQueryWrapper = new QueryWrapper<>();
                    orderPurchaseQueryWrapper.eq("order_id", orderNumber);
                    orderPurchase = orderPurchaseService.getOne(orderPurchaseQueryWrapper);
                    orderPurchaseVo = new OrderPurchaseVo();
                    if (orderPurchase != null) {
                        BeanUtils.copyProperties(orderPurchase, orderPurchaseVo);

                        //设置时间
                        String gmtModified = orderPurchase.getGmtModified();
                        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        Date placeTime = null;
                        try {
                            placeTime = dateFormat.parse(gmtModified);
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                        orderPurchaseVo.setPlaceTime(placeTime);

                        //设置国家
                        String country = buyerInfo.getCountry();
                        orderPurchaseVo.setBuyerCountry(country);

                        //设置销售员
                        String salesmanId = orders.getSalesmanId();
                        Users users = usersService.getById(salesmanId);
                        String realName = users.getRealName();
                        orderPurchaseVo.setSalesman(realName);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                //设置采购单信息
                orderSimple.setOrderPurchaseVo(orderPurchaseVo);

                //订单对应属性对拷
                BeanUtils.copyProperties(orders, orderSimple);
                //设置订单增加时间
                orderSimple.setAddTime(orders.getGmtCreated());

                //根据订单号查询订单对应的备份信息
                try {
                    OrderBack orderBack = orderBackService.getById(orderNumber);
                    BeanUtils.copyProperties(orderBack, orderSimple);
                } catch (BeansException e) {
                    e.printStackTrace();
                }

                return orderSimple;
            }).collect(Collectors.toList());

            return CommonResult.success("查询成功").put("orderSimpleList", orderSimpleList);
        }
        throw new CustomException(ReturnConstant.NO_PERMISSION_CODE
                , ReturnConstant.NO_PERMISSION_MESSAGE);
    }

    /**
     * 获取异常订单列表
     *
     * @param token
     * @return
     */
    @GetMapping("/getErrorOrders")
    @ApiOperation(value = "获取异常订单列表")
    public CommonResult getErrorOrder(String token) {
        boolean flag = permissionsService.getPermissionList(token, "36");
        if (flag) {
            CommonResult orders = null;
            try {
                orders = getOrders(token);
            } catch (Exception e) {
                throw new CustomException(ReturnConstant.GET_ERROR_LIST_ERROR_CODE
                        , ReturnConstant.GET_ERROR_LIST_ERROR_MESSAGE);
            }

            //获取json中封装的订单列表
            Object orderSimpleList = orders.get("orderSimpleList");

            //将json数据转换为对象
            String jsonString = JSON.toJSONString(orderSimpleList);
            List<OrderSimple> orderSimples = JSON.parseObject(jsonString, new TypeReference<List<OrderSimple>>() {
            });

            //查询订单中的异常订单
            QueryWrapper<Orders> wrapper = new QueryWrapper<>();
            wrapper.isNotNull("father_error");
            List<Orders> ordersList = orderSimpleService.list(wrapper);
            List<ErrorOrder> errorOrderList = new ArrayList<>();
            for (Orders order : ordersList) {
                ErrorOrder errorOrder = new ErrorOrder();
                //属性对拷
                BeanUtils.copyProperties(order, errorOrder);
                errorOrderList.add(errorOrder);
            }
            for (OrderSimple orderSimple : orderSimples) {
                for (ErrorOrder errorOrder : errorOrderList) {
                    if (orderSimple.getOrderNumber().equals(errorOrder.getOrderNumber())) {
                        BeanUtils.copyProperties(orderSimple, errorOrder);
                    }
                }
            }
            return CommonResult.success("查询成功")
                    .put("errorOrderList", errorOrderList);
        }
        throw new CustomException(ReturnConstant.NO_PERMISSION_CODE
                , ReturnConstant.NO_PERMISSION_MESSAGE);
    }

    /**
     * 删除订单
     *
     * @param orderId
     * @param token
     * @return
     */
    @SystemLog(value = "删除订单")
    @PostMapping("/deleteOrders")
    @ApiOperation(value = "删除订单")
    @Transactional
    public CommonResult deleteOrders(String orderId, String token) {
        boolean flag = permissionsService.getPermissionList(token, "36");
        if (flag) {
            Orders orders = orderSimpleService.getById(orderId);
            String amazonOrderId = orders.getAmazonOrderId();

            //根据订单号删除运单
            QueryWrapper<OrderWayBill> orderWayBillQueryWrapper = new QueryWrapper<>();
            orderWayBillQueryWrapper.eq("about_order", orderId);
            orderWayBillService.remove(orderWayBillQueryWrapper);

            //根据订单号删除采购单
            QueryWrapper<OrderPurchase> orderPurchaseQueryWrapper = new QueryWrapper<>();
            orderPurchaseQueryWrapper.eq("order_id", orderId);
            orderPurchaseService.remove(orderPurchaseQueryWrapper);

            //根据订单号删除备注信息
            contentNotesService.removeById(orderId);

            //根据订单号删除日志信息
            QueryWrapper<OperationLog> operationLogQueryWrapper = new QueryWrapper<>();
            operationLogQueryWrapper.eq("table_id", orderId);
            operationLogService.remove(operationLogQueryWrapper);

            //根据销售单号删除商品信息
            QueryWrapper<Commodity> commodityQueryWrapper = new QueryWrapper<>();
            commodityQueryWrapper.eq("amazon_order_id", amazonOrderId);
            commodityService.remove(commodityQueryWrapper);

            //根据销售单号删除买家信息
            QueryWrapper<BuyerInfo> buyerInfoQueryWrapper = new QueryWrapper<>();
            buyerInfoQueryWrapper.eq("amazon_order_id", amazonOrderId);
            buyerInfoService.remove(buyerInfoQueryWrapper);

            //根据销售单号删除卖家信息
            QueryWrapper<SellerInfo> sellerInfoQueryWrapper = new QueryWrapper<>();
            sellerInfoQueryWrapper.eq("seller_nums", amazonOrderId);
            sellerInfoService.remove(sellerInfoQueryWrapper);

            //根据订单号删除删除订单信息
            orderSimpleService.removeById(orderId);

            //根据token获取销售员信息
            String userRealName = usersService.getUserRealName(token);
            return CommonResult.success()
                    .put("list", orderId)
                    .put("salesman", userRealName);
        }
        throw new CustomException(ReturnConstant.NO_PERMISSION_CODE
                , ReturnConstant.NO_PERMISSION_MESSAGE);
    }

    /**
     * 获取亚马逊订单api
     *
     * @return
     */
    private List<OrdersV0Api> getOrdersV0Api() {
        List<AmazonAuthority> authorityList = amazonAuthorityService.list();
        List<OrdersV0Api> ordersV0ApiList = authorityList.stream().map((authority) -> {
            //通过开发人员授权信息获得订单api
            OrdersV0Api ordersV0Api = GetExample.getExampleOrder(authority);
            return ordersV0Api;
        }).collect(Collectors.toList());
        return ordersV0ApiList;
    }
}